#include "logger.h"

#include <time.h>
#include <iostream>

Logger &Logger::GetInstance()
{
    static Logger instance;
    return instance;
}

void Logger::SetLogLevel(LogLevel loglevel)
{
    m_loglevel = loglevel;
}

// 写日志 将日志信息写入到lockqueue缓冲区当中
void Logger::Log(std::string msg)
{
    m_lockqueue.enqueue(msg);
}

Logger::Logger() : m_loglevel(LogLevel::INFO)
{
    // 启动一个线程: 启动专门的写志线程
    std::thread writeLogTask([this]() {
        for (;;)
        {
            // 1.获取当一日期， 获取日志信息， 写入相应的日志文件当中
            time_t now = time(NULL);
            struct tm *now_tm = localtime(&now);

            char file_name[128];
            sprintf(file_name, "%d-%d-%d-log.txt", now_tm->tm_year+ 1900, now_tm->tm_mon + 1, now_tm->tm_mday);

            // 2.打开文件
            FILE *pf = fopen(file_name, "a+");
            if (pf == nullptr)
            {
                std::cout << "logger file: " << file_name << " open error!" << std::endl;
                exit(EXIT_SUCCESS);
            }

            // 3.获取信息增加：时-分-秒 => 将信息写入文件
            std::string msg = m_lockqueue.dequeue();
            char time_buf[128] = {0};
            sprintf(time_buf, "%d:%d:%d =>[%s] ", now_tm->tm_hour, now_tm->tm_min, now_tm->tm_sec
                                                , (m_loglevel == LogLevel::INFO ? "info" : "error"));
            msg.insert(0, time_buf);
            msg.append("\n");
            fputs(msg.c_str(), pf);
            fclose(pf);
        }
    });
    writeLogTask.detach(); // 设置分离线程
}

Logger::~Logger()
{
}
